package com.jeebey.mybatis.utils;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;

import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.jeebey.mybatis.annotation.CascadeCache;
/** 缓存清理工具类 */
public class CascadeCacheUtil {
	
	protected static Log log = LogFactory.getLog(CascadeCacheUtil.class);
	
	public static final Class<? extends Annotation> CACHE_CASCADE = CascadeCache.class;

	public static Map<String, Set<String>> cascade_cache = Maps.newHashMap();
	
	public static void initCascadeCache(String thisClass,Collection<String> classNames){
		for(String className:classNames){
			if(!StringUtils.equals(thisClass, className)){
				setCascadeCache(className);
			}
		}
	}
	
	private static void setCascadeCache(String className){
		try{
			Class<?> clazz=Class.forName(className);
			Method[] methods = clazz.getDeclaredMethods();
			for (Method method : methods) {
				if (method.isAnnotationPresent(CACHE_CASCADE)) {
					CascadeCache cascade=method.getAnnotation(CascadeCache.class);
					for(String cacheKey: cascade.value()){
						Set<String> cascades=cascade_cache.get(cacheKey);
						if(cascades==null) {cascades=Sets.newHashSet();}
						cascades.add(className);
						cascade_cache.put(cacheKey, cascades);
					}
					/**/
					for(Class<?> _clazz: cascade.clazz()){
						Set<String> cascades=cascade_cache.get(_clazz.getName());
						if(cascades==null) {cascades=Sets.newHashSet();}
						cascades.add(className);
						cascade_cache.put(_clazz.getName(), cascades);
					}
				}
			}
		}catch(Exception e){
			//log.error(e.getMessage(),e);
		}
	}
	
}
